package com.example.demo.service;

import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.Course;
import com.example.demo.repository.CourseRepository;
import com.example.demo.repository.StudentCourseRepository;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CourseService {
    private final CourseRepository courseRepository;
    private final StudentCourseRepository studentCourseRepository;
    private final ModelMapper modelMapper;

    public List<Course> getAllPublishedCourses() {
        List<Course> courses = courseRepository.findByStatus(Course.CourseStatus.PUBLISHED);
        return courses.stream()
                .map(course -> modelMapper.map(course, Course.class))
                .collect(Collectors.toList());
    }

    public Course getCourseById(Long courseId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new ResourceNotFoundException("Course not found"));
        return modelMapper.map(course, Course.class);
    }

    public boolean isStudentEnrolled(Long studentId, Long courseId) {
        return studentCourseRepository.existsByStudentIdAndCourseId(studentId, courseId);
    }

    public long getEnrolledStudentsCount(Long courseId) {
        return studentCourseRepository.countByCourseId(courseId);
    }
}